﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WCFMastering.Contracts;
using System.ServiceModel;

namespace WCFMastering.Services
{
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
    //[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, ConcurrencyMode = ConcurrencyMode.Multiple)]// Method 1: ConcurrencyMode = Multiple
    //[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, ConcurrencyMode = ConcurrencyMode.Reentrant)]// Method 2: ConcurrencyMode = Reentrant
    public class DuplexService:IDuplexService
    {
        #region Static Members

        static List<IDuplexServiceCallback> m_Callbacks = new List<IDuplexServiceCallback>();

        public static void CallClients()
        {
            Action<IDuplexServiceCallback> invoke = callback => callback.OnCallback();
            m_Callbacks.ForEach(invoke);

            //foreach (var callback in m_Callbacks)
            //{
            //    callback.OnCallback();
            //}
        }

        #endregion

        #region Implement Service Contracts

        public void DoSomeThing()
        {
            //Do Some Things
            Console.WriteLine("Excute Duplex Service:DoSomeThing!");

            IDuplexServiceCallback callback = OperationContext.Current.GetCallbackChannel<IDuplexServiceCallback>();
            callback.OnCallback();

            //try
            //{
            //    if (!m_Callbacks.Contains(callback))
            //    {
            //        m_Callbacks.Add(callback);
            //    }
            //    CallClients();
            //}
            //catch (Exception e)
            //{
            //    Console.WriteLine(e.Message);
            //}
        }

        #endregion
    }
}
